//
//  FunctionViewController.m
//  QRMaster
//
//  Created by myApple on 16/5/11.
//  Copyright © 2016年 myApple. All rights reserved.
//

#import "FunctionViewController.h"
#import "AllFunctionCardModel.h"
#import "RequestNetWork.h"
#import "FunctionCardCell.h"
#import "NoInfoPromtView.h"
#import "GenerateCardViewController.h"
#import "ChineseInclude.h"
#import "ZYPinYinSearch.h"
@interface FunctionViewController ()<UITableViewDataSource,UITableViewDelegate,NoInfoPromtViewDelegate,UISearchBarDelegate,UIGestureRecognizerDelegate>
{
    UITableView * functionCardTabelView;
    NSMutableArray * functionCardArray;
    NSMutableArray * totalArray;//总数据
    NoInfoPromtView * promtView;
    UISearchBar * functionSearchBar;
    UIButton * searchBtn;
    UISearchBar * nameSearchBar;
    UIImageView * cancelImgView;
}

@end

@implementation FunctionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = NSLocalizedString(@"functionCard", nil);
    functionCardArray = [[NSMutableArray alloc]init];
    totalArray = [[NSMutableArray alloc] init];
    self.view.backgroundColor = UIColorFromRGB(0xebebeb);
    [self prepareSearchBar];
    [self prepareTabelView];
    [self prepareNoinfoData];
    [self getFunctionInfo];
    // Do any additional setup after loading the view.
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick)];
    tap.delegate = self;
    [self.view addGestureRecognizer:tap];
}

- (void)viewWillAppear:(BOOL)animated{
    searchBtn.hidden = NO;
    [self getFunctionInfo];
    [functionCardTabelView reloadData];
}

- (void)viewWillDisappear:(BOOL)animated{
    searchBtn.hidden = YES;
    functionSearchBar.text = @"";
    functionSearchBar.hidden = YES;
}

- (void)prepareSearchBar{
    
    searchBtn = [[UIButton alloc] initWithFrame:CGRectMake(UI_SCREEN_WIDTH-16-16, 14, 16, 16)];
    [searchBtn setBackgroundImage:[UIImage imageNamed:@"ic_search"] forState:UIControlStateNormal];
    [searchBtn addTarget:self action:@selector(searchCard) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:searchBtn];

    functionSearchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, UI_SCREEN_WIDTH, 44)];
    functionSearchBar.backgroundColor = UIColorFromRGB(0xebebeb);
    functionSearchBar.barStyle = UIBarStyleDefault;
    functionSearchBar.placeholder = @"卡名";
    functionSearchBar.delegate = self;
    functionSearchBar.hidden = YES;
    [self.navigationController.navigationBar addSubview:functionSearchBar];
    
}

- (void)searchCard{
    functionSearchBar.hidden = NO;
    self.navigationController.title = @"";
}


#pragma mark - searchBarDelegate
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    searchBar.showsCancelButton = YES;
    for(UIView *view in  [[[functionSearchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[UIButton class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        }
    }

}


- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [functionCardArray removeAllObjects];
    if(![searchText isEqualToString:@""]){
        if (![ChineseInclude isIncludeChineseInString:searchText])
        {
            functionCardArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:totalArray andSearchText:searchText andSearchByPropertyName:@"functionCardName"]];
           
        }else{
            for (AllFunctionCardModel * model in totalArray) {
                if (([model.functionCardName rangeOfString:searchText].location != NSNotFound))
                {
                    [functionCardArray addObject:model];
                }
            }
        }

    }else{
        functionCardArray = [totalArray mutableCopy];
    }
    [functionCardTabelView reloadData];
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    
    [functionCardArray removeAllObjects];
    if(![searchBar.text isEqualToString:@""]){
        
        if (![ChineseInclude isIncludeChineseInString:searchBar.text])
        {
            functionCardArray = [NSMutableArray arrayWithArray: [ZYPinYinSearch searchWithOriginalArray:totalArray andSearchText:searchBar.text andSearchByPropertyName:@"functionCardName"]];
            
        }else{
            for (AllFunctionCardModel * model in totalArray) {
                if (([model.functionCardName rangeOfString:searchBar.text].location != NSNotFound))
                {
                    [functionCardArray addObject:model];
                }
            }
        }


    }else{
        functionCardArray = [totalArray mutableCopy];

    }
    [functionCardTabelView reloadData];
    [functionSearchBar resignFirstResponder];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
    functionSearchBar.hidden = YES;
    self.navigationItem.title = @"锁掌柜";
    searchBar.text = @"";
    [searchBar resignFirstResponder];
    searchBar.showsCancelButton = NO;
    functionCardArray = [totalArray mutableCopy];
    [functionCardTabelView reloadData];
}

- (void)tapClick{
    [functionSearchBar resignFirstResponder];
}

#pragma mark -- 解决tableview中手势冲突
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
    // 若为UITableViewCellContentView（即点击了tableViewCell），则不截获Touch事件
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"]) {
        return NO;
    }
    return  YES;
}

#pragma mark --------没有权限卡的提示
-(void)prepareNoinfoData
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = self.view.frame.size.height;
    promtView = [[NoInfoPromtView alloc]initWithFrame:CGRectMake(x, y, width, height)];
//    [promtView prepareViewWithPromtTitle:NSLocalizedString(@"noFunctionCard", nil)];
    [promtView prepareViewWith:@"noinformation_dark" withPromt:NSLocalizedString(@"noFunctionCard", nil)];
    promtView.hidden = YES;
    promtView.delegate = self;
    [self.view addSubview:promtView];
}

#pragma mark ---------NoinfoPromtDelegate
-(void)clickRefresh
{
    [self getFunctionInfo];
}

-(void)getFunctionInfo
{
    if ([self IsHaveNetwork]) {
        return;
    }
    [self startWaiting:nil color:nil addToView:self.view];
    NSUserDefaults * userInfo = [NSUserDefaults standardUserDefaults];
    NSMutableDictionary * postDict = [[NSMutableDictionary alloc]init];
    [postDict setValue:[userInfo objectForKey:@"uid"] forKey:@"id"];
    [postDict setValue:[userInfo objectForKey:@"token"] forKey:@"token"];
    [postDict setValue:[QRSingleton sharedQRSingleton].communityId forKey:@"communityId"];
    RequestNetWork * rnw = [[RequestNetWork alloc]init];
    [rnw initWithPath:POST(MYSELFPOWER) params:postDict block:^(id downLoadData, id error)
     {
         [self stopWaiting];
//         DDLOG(@"功能卡=%@",downLoadData);
         NSDictionary * dataDict = [downLoadData objectForKey:@"data"];
         [functionCardArray removeAllObjects];
         //总控卡
         if ([[dataDict objectForKey:@"master"]integerValue] == 1) {
             AllFunctionCardModel * model = [[AllFunctionCardModel alloc]init];
             model.buildingId = nil;
             model.buildingName  = @"";
             model.communityName = [QRSingleton sharedQRSingleton].communityName;
             model.floorId = nil;
             model.floorName = @"";
             model.functionCardName = NSLocalizedString(@"controlCard", nil);
             model.functionCardStatus = 1;
             [functionCardArray addObject:model];
         }
         //显示中因为要先显示楼栋再显示所有楼层，故先遍历所有楼栋在遍历所有楼层
         if (![dataDict[@"buildingFloor"] isEqual:[NSNull null]]) {
             NSArray * buildAndFloor = [dataDict objectForKey:@"buildingFloor"];
             for (NSDictionary * buildDict in buildAndFloor) {
                 if ([[buildDict objectForKey:@"enable"]integerValue] == 1) {
                     AllFunctionCardModel * model = [[AllFunctionCardModel alloc]init];
                     model.buildingId = [buildDict objectForKey:@"id"];
                     model.buildingName  = [buildDict objectForKey:@"name"];
                     model.communityName = [QRSingleton sharedQRSingleton].communityName;
                     model.floorId = nil;
                     model.floorName = @"";
                     model.functionCardName = [buildDict objectForKey:@"name"];
                     model.functionCardStatus = 2;
                     [functionCardArray addObject:model];
                 }
             }
             for (NSDictionary * buildDict in buildAndFloor) {
                 for (NSDictionary * floorDict in [buildDict objectForKey:@"floor"]) {
                     if ([[floorDict objectForKey:@"enable"]integerValue] == 1) {
                         AllFunctionCardModel * model = [[AllFunctionCardModel alloc]init];
                         model.buildingId = [buildDict objectForKey:@"id"];
                         model.buildingName  = [buildDict objectForKey:@"name"];
                         model.communityName = [QRSingleton sharedQRSingleton].communityName;
                         model.floorId = [floorDict objectForKey:@"id"];
                         model.floorName = [floorDict objectForKey:@"name"];
                         model.functionCardName = [floorDict objectForKey:@"name"];
                         model.functionCardStatus = 3;
                         [functionCardArray addObject:model];
                     }
                 }
             }

         }
         totalArray = [functionCardArray mutableCopy];
         if (functionCardArray.count == 0 && downLoadData != nil) {
             promtView.hidden = NO;
         }
         if (functionCardArray.count != 0) {
             promtView.hidden = YES;
         }
         if (error != nil) {
             [PromptInfoView showMessage:[error objectForKey:@"info"]];
         }
         [functionCardTabelView reloadData];
     }];
}

-(void)prepareTabelView
{
    float x = 0;
    float y = 0;
    float width = UI_SCREEN_WIDTH;
    float height = UI_SCREEN_HEIGHT - 64 - 49 - 44 - 16;
    functionCardTabelView = [[UITableView alloc]initWithFrame:CGRectMake(x, y, width, height) style:UITableViewStylePlain];
    functionCardTabelView.delegate = self;
    functionCardTabelView.dataSource = self;
    functionCardTabelView.tableFooterView = [UIView new];
    functionCardTabelView.backgroundColor = UIColorFromRGB(0xebebeb);
    [self.view addSubview:functionCardTabelView];
    
    x = 0;
    y = 0;
    height = 16.0;
    UIView * headerView = [[UIView alloc]initWithFrame:CGRectMake(x, y, width, height)];
    headerView.backgroundColor = UIColorFromRGB(0xebebeb);
    functionCardTabelView.tableHeaderView = headerView;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return functionCardArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 56.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * identityId = @"cellId";
    FunctionCardCell * cell =[tableView dequeueReusableCellWithIdentifier:identityId];
    if (!cell) {
        cell = [[FunctionCardCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identityId];
    }
    AllFunctionCardModel * cardModel = functionCardArray[indexPath.row];
    cell.communityName = cardModel.communityName;
    cell.functionCardName = cardModel.functionCardName;
    cell.buildingName = cardModel.buildingName;
    cell.floorName = cardModel.floorName;
    cell.functionCardStatus = cardModel.functionCardStatus;
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AllFunctionCardModel * model = functionCardArray[indexPath.row];
    GenerateCardViewController * gcvc = [[GenerateCardViewController alloc]initwithFunctionCardModel:model];
    [self.navigationController pushViewController:gcvc animated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
